/*@autor
 *  vindn : 19/08/05
 */
package appman.ui.grappareader;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.io.Serializable;
import org.isam.exehda.Exehda;
import org.isam.exehda.services.Worb;
import appman.ApplicationManagerRemote;
import appman.clustering.*;
import appman.parser.ApplicationDescription;

/**
 * This class obtain DAG information and generates a coordinate file to allow
 * DAG drawing. This class gets the ContactAddress to conect via WORB with
 * AppMan's Application Manager. Using this ContactAddress, it can invoke remote
 * methods of the ApplicationManager, and thus obtain the DAG, and the status of
 * the tasks. It reads the dot file generated by DAG_DSC and calls dot command
 * to obtain the graphical coordinates. Having all this information, it
 * instantiates the window where the DAG is presented, with status information
 * being updated online.
 * 
 * @author dalto
 */

public class Reader implements Serializable {

	protected static String inputFilePath = new String(
			"/home/SO/dalto/eclipse/workspace/appman-mgc/grappaOut.txt");

	protected static ShowWindow window;

	protected DataInputStream inputFile;

	protected long fileSize;//Ultimo tamanho do arquivo desde q foi atualizado.

	static ApplicationManagerRemote appman = null;

	public Reader() throws FileNotFoundException {
		inputFile = new DataInputStream(new FileInputStream(inputFilePath));

	}

	private static String colorToString(int intColor) {
		String color = "";
		switch (intColor) {
		case 0:
			color = "green";
			break;

		case 1:
			color = "yellow";
			break;

		case 2:
			color = "blue";
			break;

		case 3:
			color = "red";
			break;
		}

		return color;
	}

	public static void main(String[] argv) {

		DAG_DSC dag_dsc;
		int nNodes;
		String names;
		int colors;
		RandomAccessFile file;

		String contact_address;
		ApplicationDescription apd;

		//Executar o DOT para gerar o arquivo com as coordenadas para a leitura
		// do GRAPPA

		//Tem q ter o DOT instalado senao nao funciona...
		/**
		 * Executing DOT to generate a file with the positions. The GRAPPA need
		 * this file for read the positions. The DOT must be installed. In
		 * appman have only the executables of DOT, in somes linux versions
		 * could be miss any libraries for execute DOT. Our version is
		 * Scientific Linux 2.0 = Fedora Core 3.0
		 */
		try {
			// Execute a command - run a unix script to get DAG formatting
			//String directory = "../../dot/";
			String directory = "../../dot/dotneato/"; // DOT executables
													  // directory
			String directoryTMP = "./";
			//String formatCommand = directory+"formatDemo.sh <
			// "+directoryTMP+"graphiz.dot > "+directoryTMP+"teste333.dot";
			String formatCommand = directory + "dot " + directoryTMP
					+ "graphiz.dot -o " + directoryTMP + "coordenadas.dot";
			String[] commands = new String[] { "/bin/sh", "-c", formatCommand };

			Process child = Runtime.getRuntime().exec(commands);

			// Get the input stream and read from it
			// Used to sincronize command execution
			InputStream in = child.getInputStream();
			int c;
			while ((c = in.read()) != -1) {
				System.out.print((char) c);
			}
			in.close();
			/////////////////////////////////////////////////

		} catch (IOException e) {
			System.out.println("ERRRO NA EXECUCAO!!!");
		}

		/**
		 * Get contact address of Application Manager
		 */
		try {
			file = new RandomAccessFile("appman_contact_adress.txt", "r");
			contact_address = file.readLine();
			file.close();

			Worb worb = (Worb) Exehda.getService(Worb.SERVICE_NAME);
			appman = (ApplicationManagerRemote) worb.lookupService(
					contact_address, ApplicationManagerRemote.class);
			System.out.print("[APPMAN-GRAPPAREADER]: " + appman);

		} catch (Exception e) {
			e.printStackTrace();
		}

		//appman =
		// (ApplicationManagerRemote)activator.getRemoteObjectReference(contact_address,
		// ApplicationManagerRemote.class);
		try {

			//appman.teste();
			//int i = appman.getApplicationStateRemote();
			window = new ShowWindow();

			window.showDAG("coordenadas.dot");

			int numberOfFinished = 0;
			boolean end = true;
			while (true) {
				apd = appman.getApplicationDescription();
				dag_dsc = apd.applicationDAG;
				nNodes = dag_dsc.getNumberOfNodes();
				end = true;
				numberOfFinished = 0;
				for (int i = 0; i < nNodes; i++) {
					window
							.changeColorNode(dag_dsc.getNameByIndex(i),
									colorToString((dag_dsc
											.getNodeByIndex(i)).status));
					//System.out.print("NODE: "+names[i]+"
					// COLOR:"+colorToString(colors[i])+"\n\n");
					if ((dag_dsc.getNodeByIndex(i)).status != 2) {
						end = false;
					} else {
						numberOfFinished++;
						window.setNumberOfFinishedTasks(numberOfFinished);
					}

					//if(end) break;
				}
				Thread.sleep(1000);
			}
			//Thread.yield();
		} catch (Exception e) {
			System.out.println("\n[GRAPPAREADER]: " + e + "\n\n");
			e.printStackTrace();
		}

	}

}